﻿using NCS.IConnect.Core.IoC;
using NCS.IConnect.Core.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;

namespace NCS.IConnect.Core.WebApi
{
    /// <summary>
    /// A custom HttpControllerActivator which uses ServiceLocator to activate HttpController.
    /// </summary>
    public class ServiceLocatableHttpControllerActivator : IHttpControllerActivator
    {
        #region Properties
        /// <summary>
        /// Gets the service locator.
        /// </summary>
        /// <value>
        /// The service locator.
        /// </value>
        public IServiceLocator ServiceLocator { get; private set; }
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceLocatableHttpControllerActivator"/> class.
        /// </summary>
        /// <param name="serviceLocatorName">Name of the service locator.</param>
        public ServiceLocatableHttpControllerActivator(string serviceLocatorName = null): this(ServiceLocatorFactory.GetServiceLocator(serviceLocatorName))
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceLocatableHttpControllerActivator"/> class.
        /// </summary>
        /// <param name="serviceLocator">The service locator.</param>
        public ServiceLocatableHttpControllerActivator(IServiceLocator serviceLocator)
        {
            Guard.ArgumentNotNull(serviceLocator, "serviceLocator");
            this.ServiceLocator = serviceLocator;
        }
        #endregion

        #region Public Methods
        /// <summary>
        /// Creates the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="controllerDescriptor">The controller descriptor.</param>
        /// <param name="controllerType">Type of the controller.</param>
        /// <returns>The activated HttpController.</returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")]
        public IHttpController Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
        {
            return this.ServiceLocator.GetService(controllerType) as IHttpController;
        }
        #endregion
    }
}
